<?php
namespace App\Api\Controllers;
use Common\ApiController;
use Common\Models\User;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/4/18
 * Time: 13:04
 */
class UploadController extends ApiController
{
    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 上传头像到七牛
     * 返回上传的图片地址
     */
    public function  upload_fileAction(){
        if(empty($_FILES)){
            $this->fail(-1,'请上传图片');
        }
        $img_type=explode('/',$_FILES["file"]["type"])[1];
        $filetype = ['mp3','mpeg','jpg', 'jpeg', 'gif', 'bmp', 'png','octet-stream'];
        if(!in_array($img_type, $filetype)) {
            $this->fail(-1,'上传的类型错误,请上传jpg,jpeg,gif,bmp,png,mp3类型');
        }
        $type = substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], '.')+1);       //获取文件的后缀
        //处理安卓的流对象
        $file_path="uploadfile/".time().rand(1000000,9999999).'.'.$type;
        $qiniua = $this->qiniu->upload($_FILES["file"]["tmp_name"],$file_path);
        if($qiniua['code']){
            $data['file_name']=$qiniua['data'];
            $this->ok($data);
        }else{
            $this->fail(-1,'图片上传失败');
        }
    }


    /**
     * 上传头像
     */
    public function avatarAction(){
        if(empty($_FILES)){
            $this->fail(-1,'请上传图片');
        }
        $img_type=explode('/',$_FILES["file"]["type"])[1];
        $filetype = ['jpg', 'jpeg', 'gif', 'bmp', 'png','octet-stream'];
        if(!in_array($img_type, $filetype)) {
            $this->fail(-1,'上传的图片类型错误,请上传jpg,jpeg,gif,bmp,png类型');
        }
        $user = new User();
        $user_info = $user->find_by_firstId((int)$this->user_info['id']);
        if(file_exists($user_info['avatar'])){
            //unlink($user_info['avatar']);
        }
        //$type=explode('/',$_FILES["avatar"]["type"])[1];
        $type = substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], '.')+1);       //获取文件的后缀
        //处理安卓的流对象
        $file_path="images/".time().rand(1000000,9999999).'.'.$type;
        $qiniua = $this->qiniu->upload($_FILES["file"]["tmp_name"],$file_path);
        if($qiniua['code']){
            $user_info['avatar'] = "http://qn.enshitc.com/".$file_path;
            $data['avatar']=$user_info['avatar'];
            $user->save_user($user_info);
            $this->cache->del_cache("user_".$this->user_info['id']);
            return $this->ok($data);
        }else{
            $this->fail(-1,'图片上传失败');
        }
    }
}